package com.cxdr.awsips.packing.processor;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.log4j.Logger;

import com.cxdr.awsips.packing.bean.FileType;
import com.cxdr.awsips.packing.bean.PackLog;
import com.cxdr.awsips.packing.config.SystemConfig;
import com.cxdr.awsips.packing.logger.LogFactory;
import com.cxdr.awsips.packing.pool.BaseQueue;

public class FilePacker extends BaseProcessor {
	// 待打包的文件
	public static final BaseQueue<PackLog> FileQueue = new BaseQueue<PackLog>();
	public static final BaseQueue<PackLog> PackedFileQueue = new BaseQueue<PackLog>();
	private static Logger logger = LogFactory.makeNewLogger(FilePacker.class);
	private static int[][] packCnt= new int[2][FileType.values().length];
	private static boolean isDeleteSource = false;
	private int maxFile = -1;
	private ArrayList<PackLog>[][] files = new ArrayList[2][]; //数组0 是国家站,数组1是区域站
	public FilePacker(){
		if(SystemConfig.get("isdelete-source")==null){
			isDeleteSource = Boolean.parseBoolean(SystemConfig.get("isdelete-source"));
		} 
		if (SystemConfig.get("num.file-pack-max") != null) {
			maxFile = Integer.parseInt(SystemConfig.get("num.file-pack-max"));
			logger.debug("maxFile:"+maxFile);
		}
		files[0] = new ArrayList[FileType.values().length];
		files[1] = new ArrayList[FileType.values().length];
		for(int i=0;i<FileType.values().length;i++){
			files[0][i]=new ArrayList<PackLog>();//国家站文件
			files[1][i]=new ArrayList<PackLog>();//区域站文件
		}
	}
	@Override
	public void run() {
		int[][] fileCnt =new int[2][FileType.values().length] ;
		int handedCnt = 0;
		while (!isFinish()) {
			PackLog file = FileQueue.take();
		//	FileQueue.isEmpty();
			if (file == null) {
				continue;
			}
			FileType type = FileType.valueOf(file.getFile_type());
			int fileTypeIndex = type.ordinal();
			int isReg = 0;
			if(file.getSource_file().contains("REG")){
				isReg = 1;
			}
			files[isReg][fileTypeIndex].add(file);
			fileCnt[isReg][fileTypeIndex]++;
			handedCnt++;
			// 如果扫描完了并且取完了文件，或者已经达到最大文件数
			if (maxFile > 0 && fileCnt[isReg][fileTypeIndex] >= maxFile) {
				packFile(files[isReg][fileTypeIndex],type,isReg);
				files[isReg][fileTypeIndex].clear();
				fileCnt[isReg][fileTypeIndex] = 0;
			}
			if(handedCnt>=FileScaner.getScanedCnt()){
				for(FileType _type:FileType.values()){
					if(_type==FileType.AZ){
						continue;
					}
					packFile(files[0][_type.ordinal()],_type,0);
					files[0][_type.ordinal()].clear();
					fileCnt[0][_type.ordinal()] = 0;
					packFile(files[1][_type.ordinal()],_type,1);
					files[1][_type.ordinal()].clear();
					fileCnt[1][_type.ordinal()] = 0;
				}
			}
			logger.info("处理"+file.getSource_file()+"打包 结束");
		}
		logger.info("打包线程结束");
	}
	
	private void packFile(ArrayList<PackLog> files,FileType type,int isReg) {
		if(files==null||files.isEmpty()){
			return ;
		}
		List<String> content_lines = new LinkedList<String>();
		String targetName = makePackName(type,isReg);
		logger.info("开始打包文件"+targetName);
		File packFile = new File(SystemConfig.get("path.pack") + File.separator + targetName);
		if (!files.isEmpty()) {
			type = FileType.valueOf(files.get(0).getFile_type());
		}
		for (PackLog log : files) {
			File file = new File(SystemConfig.get("path.source") + File.separator + log.getSource_file());
			try {
				List<String> lines = FileUtils.readLines(file);
				//黄迎调整雨量BUG，将最后一行空去掉
				if(lines.get(lines.size()-1)==""||lines.get(lines.size()-1).length()==0) lines.remove(lines.size()-1);
				while(SystemConfig.get("str.file-last-line").equals(lines.get(lines.size()-1))){
					lines.remove(lines.size()-1);
				}
//				lines.remove(lines.size()-1);
				content_lines.addAll(lines);
				log.setTarget_file(targetName);
				PackedFileQueue.add(log.clone());
				StorePackLogProccessor.LogQueue.add(log);
				//备份文件
				String backpath = SystemConfig.get("path.backup");
				if(backpath!=null){
					file.renameTo(new File(backpath+File.separator+log.getSource_file()));
				}
			} catch (IOException e) {
				e.printStackTrace();
				logger.error("打包出错",e);
				return;
			}catch(Exception e){
				e.printStackTrace();
				logger.error("打包出错",e);
				return;
			}
		}
		content_lines.add(SystemConfig.get("str.file-last-line"));
		try {
			FileUtils.writeLines(packFile, content_lines);
		} catch (IOException e) {
			logger.error("打包异常",e);
			e.printStackTrace();
			return;
		}finally{
			files.clear();
		}
		logger.info("文件："+targetName+" 完成");
	}

	private String makePackName(FileType type,int isReg) {
		StringBuilder fileName = new StringBuilder();
		// 'E:气象要素报,R:辐射报,D:日数据包,Z:状态报,N:雨量报 AZ:其他格式'
		String endStr = "";
		switch (type) {
		case E:
			fileName.append("Z_SURF_C");
			endStr = "O_AWS_FTM";
			break;
		case R:
			fileName.append("Z_RADI_C");
			endStr="O_ARS_FTM";
			break;
		case D:
			fileName.append("Z_SURF_C");
			endStr = "O_AWS_DAY";
			break;
		case Z:
			fileName.append("Z_SURF_C");
			endStr = "R_AWS_FTM";
			break;
		case N:
			fileName.append("Z_SURF_C");
			endStr = "O_AWS-PRF_FTM";
			break;
		case AZ:
			fileName.append("Z_O_OTHER_C");
			endStr = "";
			break;
		}
	//	packCnt[type.ordinal()]++;
		fileName.append("_").append(SystemConfig.get("str.CCCC"));
		if(isReg==1){
			fileName.append("-REG");
		}
		fileName.append("_").append(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
		//fileName.append("_").append(packCnt[isReg][type.ordinal()]++);
		fileName.append("_").append(endStr);
		fileName.append(".txt");
		return fileName.toString();
	}

	
}
